package com.maikec.utils.mybatis.provider;

import org.apache.ibatis.jdbc.SQL;
import org.springframework.util.StringUtils;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * insert代理类
 * @author maikec
 * @date 2018/7/12
 */
public class InsertProvider<T> implements Provider{
    /**
     * 保存
     * @param t t
     * @return sql
     * @throws Exception exception
     */
    public String insert(T t) throws Exception {
        if (null == t) {
            throw new NullPointerException(t.getClass().getName() + " is null");
        }
        return new SQL(){
            {
                INSERT_INTO(getTableName(t));
                Map<String, String[]> colAndVal = getColumns(t);
                INTO_COLUMNS(colAndVal.get("columns"));
                INTO_VALUES(colAndVal.get("values"));
            }
        }.toString();
    }

    /**
     * 获取字段和字段值
     * @param t t
     * @return HashMap<String, String[]>  hashMap<String, String[]>
     * @throws Exception exception
     */
    private HashMap<String, String[]> getColumns(T t) throws Exception{
        Map<String, String[]> map = new HashMap<String, String[]>(16);
        List<String> columns =  new ArrayList<>();
        List<Object> values = new ArrayList<>();
        for (Field field : t.getClass().getDeclaredFields()) {
            field.setAccessible(true);
            Object object = field.get(t);
            if (("id".equals(field.getName())) && object.toString().equals("0")) {
                continue;
            }
            if(!StringUtils.isEmpty(object)) {
                columns.add(field.getName());
                if ("java.util.Date".equals(field.getType().getName())) {
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    object = simpleDateFormat.format(object);
                }
                values.add("'"+object.toString()+"'");
            }
        }
        String[] columnsStr = columns.toArray(new String[0]);
        String[] valuesStr = values.toArray(new String[0]);
        map.put("columns", columnsStr);
        map.put("values", valuesStr);
        return (HashMap<String, String[]>) map;
    }
}
